
import request from "@/utils/request";

export interface RIGHT_IDS {
  ONLINE: string;
  DICT: string;
  DOC: string;
  WORD: string;
  IMAGE: string;
  SCREENSHOT: string;
  PLAY: string;
}
export const RIGHT_IDS: RIGHT_IDS = {
  ONLINE: import.meta.env.VITE_APP_ONLINE_RID as string,
  DICT: import.meta.env.VITE_APP_DICT_RID as string,
  DOC: import.meta.env.VITE_APP_DOC_RID as string,
  WORD: import.meta.env.VITE_APP_WORD_RID as string,
  IMAGE: import.meta.env.VITE_APP_IMAGE_RID as string,
  SCREENSHOT: import.meta.env.VITE_APP_SCREENSHOT_RID as string,
  PLAY: import.meta.env.VITE_APP_PLAY_RID as string
};

export const TYPE_WHITELIST = Object.keys(RIGHT_IDS);

export const getRightIdByType = (type: keyof RIGHT_IDS): string => {
  return RIGHT_IDS[type];
};

interface RightInfoOptions {
  isCache?: boolean,
  expireInterval?: number
}
export const getRightInfo = (type: string, options: RightInfoOptions) => {
  const { isCache = true, expireInterval = 60 * 60 * 1 * 1000 } = options
  const storeKey = `${type}_RIGHT`

  return new Promise((resolve) => {
    const storageValue = localStorage.getItem(storeKey)
    let data = null
    if (storageValue) {
      try {
        data = JSON.parse(storageValue)
      } catch (error) {
        data = null
      }
    }

    const rightId = getRightIdByType(type as keyof RIGHT_IDS)
    resolve({ data, rightId })
  }).then(async (res: any) => {
    return new Promise((resolve, reject) => {
      const { data, rightId } = res

      if (
        data &&
        data._expire &&
        Number(data._expire || 0) &&
        Number(new Date(Number(data._expire))) > Date.now()
      ) {
        resolve(data)
        return
      }

      request({
        url: import.meta.env.VITE_APP_FY_BASE_API + 'translation/webs/rest_usage',
        method: 'get',
        headers: {
          "content-type": "application/json"
        },
        params: {
          right_id: rightId
        }
      }).then((res: any) => {
        if (res.code !== 200) {
          reject()
          return
        }

        const nowTime = Date.now()
        const expireTime = nowTime + expireInterval
        if (res.data.rest_limit < 0) {
          res.data.rest_limit = 0
        }
        res.data._time = nowTime
        res.data._expire = expireTime

        localStorage.setItem(storeKey, res.data)
        resolve(res.data)
      }).catch(reject)
    })
  })
}
